import 'dart:io';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:url_launcher/url_launcher.dart';
import '../apis/app.dart';
import '../model/app_update_info.dart';
import '../static/custom_code.dart';

/// 应用更新工具类
class AppUpdateUtil {
  /// 检查更新
  static Future<void> checkUpdate({bool showNoUpdateToast = false}) async {
    try {
      // 获取当前应用信息
      PackageInfo packageInfo = await PackageInfo.fromPlatform();
      int currentVersionCode = int.parse(packageInfo.buildNumber);
      String platform = Platform.isAndroid ? 'android' : 'ios';
      
      Get.log('📱 当前版本: ${packageInfo.version} (build: $currentVersionCode)');
      Get.log('🔍 检查更新中... 平台: $platform');
      
      // 调用检查更新API
      final response = await AppUpdateApi.checkUpdate(
        platform: platform,
        versionCode: currentVersionCode,
      );
      
      if (response.code == StatusCode.getSuccess) {
        final updateInfo = AppUpdateInfo.fromJson(response.data);
        
        if (updateInfo.needUpdate) {
          Get.log('🆕 发现新版本: ${updateInfo.versionName} (build: ${updateInfo.versionCode})');
          Get.log('📝 更新内容: ${updateInfo.updateContent}');
          Get.log('⚠️ 强制更新: ${updateInfo.forceUpdate}');
          
          // 显示更新对话框
          _showUpdateDialog(updateInfo);
        } else {
          Get.log('✅ 已是最新版本');
          if (showNoUpdateToast) {
            Get.snackbar(
              '版本检查',
              '当前已是最新版本',
              snackPosition: SnackPosition.BOTTOM,
              duration: const Duration(seconds: 2),
            );
          }
        }
      } else {
        Get.log('❌ 检查更新失败: ${response.msg}');
      }
    } catch (e) {
      Get.log('❌ 检查更新异常: $e');
      if (showNoUpdateToast) {
        Get.snackbar(
          '检查更新失败',
          '网络连接失败，请稍后再试',
          snackPosition: SnackPosition.BOTTOM,
        );
      }
    }
  }
  
  /// 显示更新对话框
  static void _showUpdateDialog(AppUpdateInfo updateInfo) {
    Get.dialog(
      WillPopScope(
        // 如果是强制更新，禁止返回键关闭
        onWillPop: () async => !updateInfo.forceUpdate,
        child: AlertDialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16),
          ),
          title: Row(
            children: [
              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: const Color(0xFF6366F1).withOpacity(0.1),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: const Icon(
                  Icons.system_update,
                  color: Color(0xFF6366F1),
                  size: 28,
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      '发现新版本',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 2),
                    Text(
                      'v${updateInfo.versionName}',
                      style: const TextStyle(
                        fontSize: 13,
                        color: Color(0xFF9CA3AF),
                        fontWeight: FontWeight.normal,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              if (updateInfo.forceUpdate)
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                  decoration: BoxDecoration(
                    color: const Color(0xFFFEE2E2),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: const Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Icon(Icons.warning, color: Color(0xFFDC2626), size: 16),
                      SizedBox(width: 6),
                      Text(
                        '强制更新',
                        style: TextStyle(
                          color: Color(0xFFDC2626),
                          fontSize: 13,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ],
                  ),
                ),
              if (updateInfo.forceUpdate) const SizedBox(height: 16),
              const Text(
                '更新内容：',
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                  color: Color(0xFF374151),
                ),
              ),
              const SizedBox(height: 8),
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: const Color(0xFFF9FAFB),
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: const Color(0xFFE5E7EB)),
                ),
                child: Text(
                  updateInfo.updateContent,
                  style: const TextStyle(
                    fontSize: 14,
                    color: Color(0xFF6B7280),
                    height: 1.5,
                  ),
                ),
              ),
            ],
          ),
          actions: [
            // 非强制更新时显示"稍后再说"按钮
            if (!updateInfo.forceUpdate)
              TextButton(
                onPressed: () => Get.back(),
                child: const Text(
                  '稍后再说',
                  style: TextStyle(color: Color(0xFF9CA3AF)),
                ),
              ),
            ElevatedButton(
              onPressed: () {
                Get.back();
                _downloadUpdate(updateInfo);
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFF6366F1),
                foregroundColor: Colors.white,
                padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
              ),
              child: const Text(
                '立即更新',
                style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600),
              ),
            ),
          ],
        ),
      ),
      // 非强制更新时允许点击外部关闭
      barrierDismissible: !updateInfo.forceUpdate,
    );
  }
  
  /// 下载更新
  static Future<void> _downloadUpdate(AppUpdateInfo updateInfo) async {
    try {
      final Uri url = Uri.parse(updateInfo.downloadUrl);
      
      // 检查是否可以启动URL
      if (await canLaunchUrl(url)) {
        Get.log('📥 开始下载: ${updateInfo.downloadUrl}');
        await launchUrl(url, mode: LaunchMode.externalApplication);
      } else {
        Get.log('❌ 无法打开下载链接: ${updateInfo.downloadUrl}');
        Get.snackbar(
          '下载失败',
          '无法打开下载链接，请稍后再试',
          snackPosition: SnackPosition.BOTTOM,
        );
      }
    } catch (e) {
      Get.log('❌ 下载更新异常: $e');
      Get.snackbar(
        '下载失败',
        '打开下载页面失败: $e',
        snackPosition: SnackPosition.BOTTOM,
      );
    }
  }
}

